<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>任务分配系统</title>
    <style>
        :root {
    --primary-color: #5c6bc0;
    --primary-light: #8e99f3;
    --primary-dark: #26418f;
    --secondary-color: #26a69a;
    --secondary-light: #64d8cb;
    --secondary-dark: #00766c;
    --background: #f5f7fa;
    --card-bg: #ffffff;
    --text-primary: #2d3748;
    --text-secondary: #4a5568;
    --border-radius: 12px;
    --box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

body {
    font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
    background-color: var(--background);
    color: var(--text-primary);
    line-height: 1.6;
}

.container {
    display: flex;
    min-height: 100vh;
    padding: 20px;
    gap: 20px;
    max-width: 1600px;
    margin: 0 auto;
    align-items: stretch;
}

.left-panel {
    width: 60%;
    background-color: var(--card-bg);
    padding: 25px;
    border-radius: var(--border-radius);
    box-shadow: var(--box-shadow);
    overflow-y: auto;
    transition: all 0.3s ease;
}

.right-panel {
    width: 40%;
    padding: 25px;
    background-color: var(--card-bg);
    border-radius: var(--border-radius);
    box-shadow: var(--box-shadow);
    position: sticky;
    top: 20px;
    height: calc(100vh - 40px);
    overflow: hidden;
    display: flex;
    flex-direction: column;
    opacity: 0;
    transform: translateX(20px);
    visibility: hidden;
    transition: opacity 0.3s ease, transform 0.3s ease, visibility 0.3s;
    min-height: 300px;
}

.right-panel.visible {
    opacity: 1;
    transform: translateX(0);
    visibility: visible;
}

h2 {
    color: var(--primary-dark);
    margin-bottom: 20px;
    font-weight: 600;
    border-bottom: 2px solid var(--primary-light);
    padding-bottom: 10px;
}

.projects-container {
    margin-top: 15px;
}

.project-item {
    position: relative;
    margin-bottom: 20px;
    border-radius: var(--border-radius);
    overflow: hidden;
    transition: transform 0.2s ease;
}

.project-item:hover {
    transform: translateY(-2px);
}

.project-header {
    background: linear-gradient(135deg, var(--primary-color), var(--primary-light));
    color: white;
    padding: 15px 20px;
    cursor: pointer;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 500;
    transition: all 0.3s ease;
    position: relative;
    z-index: 2;
}

.project-header:hover {
    background: linear-gradient(135deg, var(--primary-dark), var(--primary-color));
}

.subtasks-container {
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

.subtasks-container.show {
    max-height: 600px;
}

.subtasks-list {
    max-height: 550px;
    overflow-y: auto;
    padding: 10px 0;
    background-color: rgba(245, 247, 250, 0.7);
    scrollbar-width: thin;
}

.subtasks-list::-webkit-scrollbar {
    width: 6px;
}

.subtasks-list::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

.subtasks-list::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}

.subtasks-list::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

.subtask-item {
    padding: 12px 25px;
    cursor: pointer;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
}

.subtask-item:before {
    content: "•";
    color: var(--secondary-color);
    margin-right: 10px;
    font-size: 20px;
}

.subtask-item:hover {
    background-color: rgba(92, 107, 192, 0.1);
    color: var(--primary-dark);
    transform: translateX(5px);
}

.task-assignment {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.employees-list {
    flex: 1;
    overflow-y: auto;
    margin: 20px 0;
    padding-right: 10px;
}

.employee-item {
    display: flex;
    align-items: center;
    padding: 15px;
    background-color: var(--card-bg);
    margin-bottom: 10px;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    transition: all 0.2s ease;
}

.employee-item:hover {
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
}

.assign-btn {
    padding: 12px 24px;
    background: linear-gradient(135deg, var(--secondary-color), var(--secondary-light));
    color: white;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-size: 16px;
    font-weight: 500;
    align-self: flex-end;
    transition: all 0.3s ease;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.assign-btn:hover {
    background: linear-gradient(135deg, var(--secondary-dark), var(--secondary-color));
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
}

.placeholder {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    color: var(--text-secondary);
    font-size: 18px;
    text-align: center;
    opacity: 0.8;
}

.checkbox-container {
    display: block;
    position: relative;
    padding-left: 35px;
    cursor: pointer;
    user-select: none;
    width: 100%;
}

.checkbox-container input {
    position: absolute;
    opacity: 0;
    cursor: pointer;
    height: 0;
    width: 0;
}

.checkmark {
    position: absolute;
    top: 0;
    left: 0;
    height: 22px;
    width: 22px;
    background-color: #f0f0f0;
    border-radius: 6px;
    transition: all 0.2s ease;
}

.checkbox-container:hover input ~ .checkmark {
    background-color: #e0e0e0;
}

.checkbox-container input:checked ~ .checkmark {
    background-color: var(--secondary-color);
}

.checkmark:after {
    content: "";
    position: absolute;
    display: none;
}

.checkbox-container input:checked ~ .checkmark:after {
    display: block;
}

.checkbox-container .checkmark:after {
    left: 8px;
    top: 4px;
    width: 5px;
    height: 10px;
    border: solid white;
    border-width: 0 2px 2px 0;
    transform: rotate(45deg);
}

.notification {
    position: fixed;
    top: 20px;
    right: 20px;
    padding: 15px 25px;
    border-radius: 8px;
    color: white;
    font-weight: 500;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    transform: translateX(120%);
    transition: transform 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
    z-index: 1000;
}

.notification.show {
    transform: translateX(0);
}

.notification.success {
    background-color: #4caf50;
}

.notification.warning {
    background-color: #ff9800;
}

.notification.error {
    background-color: #f44336;
}

@media (max-width: 992px) {
    .container {
        flex-direction: column;
        padding: 15px;
    }

    .left-panel, .right-panel {
        width: 100%;
    }

    .left-panel {
        margin-bottom: 20px;
    }

    .right-panel {
        position: relative;
        top: auto;
        height: auto;
        max-height: 50vh;
    }

    .subtasks-container.show {
        max-height: 500px;
    }

    .subtasks-list {
        max-height: 450px;
    }
}

.no-projects {
    text-align: center;
    padding: 20px;
    color: #666;
}

.subtask-item.loading,
.employee-item.loading {
    color: #999;
    font-style: italic;
}

.subtask-item.no-subtasks,
.employee-item.no-employees {
    color: #666;
    font-style: italic;
}

.subtask-item.error,
.employee-item.error {
    color: #f44336;
}

.subtask-item.active {
    background-color: rgba(92, 107, 192, 0.2);
    font-weight: bold;
}
    </style>
</head>
<body>
    {% csrf_token %}
    <div class="container">
        <div class="left-panel">
            <h2>项目列表</h2>
            <div class="projects-container" id="projectsContainer">
                {% if all_project %}
                    {% for project in all_project %}
                    <div class="project-item" data-project-id="{{ project.project_id }}">
                        <div class="project-header">
                            <span>{{ project.project_name }}</span>
                            <span class="arrow">▼</span>
                        </div>
                        <div class="subtasks-container">  <!-- 新增容器 -->
                            <div class="subtasks-list">
                                {% if selected_project_id == project.project_id|stringformat:"s" and subprojects %}
                                    {% for subtask in subprojects %}
                                    <div class="subtask-item"
                                         data-subtask-id="{{ subtask.id }}"
                                         data-project-id="{{ project.project_id }}">
                                        {{ subtask.content }} (工作量: {{ subtask.predicted_effort|default:"0" }})
                                    </div>
                                    {% endfor %}
                                {% else %}
                                    <div class="subtask-item loading">点击项目加载子任务...</div>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                {% else %}
                    <div class="no-projects">
                        <p>您目前没有管理的项目</p>
                    </div>
                {% endif %}
            </div>
        </div>

        <div class="right-panel" id="rightPanel">
            <div class="task-assignment" id="taskAssignment" style="display: none;">
                <h2 id="selectedTaskTitle">分配子任务: </h2>
                <div class="employees-list" id="employeesList">
                    {% if selected_project_id and users %}
                        {% for user in users %}
                        <div class="employee-item">
                            <label class="checkbox-container">
                                {{ user.full_name }}
                                <input type="checkbox" value="{{ user.id }}">
                                <span class="checkmark"></span>
                            </label>
                        </div>
                        {% endfor %}
                    {% else %}
                        <div class="employee-item no-employees">请先选择项目</div>
                    {% endif %}
                </div>
                <button class="assign-btn" id="assignBtn">分配子任务</button>
            </div>

            <div class="placeholder" id="placeholder">
                <p>请展开项目并选择子任务进行分配</p>
            </div>
        </div>
    </div>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // 获取CSRF令牌
        const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
        const rightPanel = document.getElementById('rightPanel');
        let currentlyExpandedProject = null;
        let currentSubtask = null;

        // 阻止子任务列表滚动时事件冒泡
        document.addEventListener('wheel', function(e) {
            const subtaskList = e.target.closest('.subtasks-list');
            if (subtaskList) {
                const isScrollable = subtaskList.scrollHeight > subtaskList.clientHeight;
                const isAtTop = subtaskList.scrollTop === 0;
                const isAtBottom = subtaskList.scrollTop + subtaskList.clientHeight === subtaskList.scrollHeight;

                if (isScrollable && !(isAtTop && e.deltaY < 0) && !(isAtBottom && e.deltaY > 0)) {
                    e.stopPropagation();
                }
            }
        }, { passive: false });

        // 项目点击事件 - 加载子任务
        // 修改后的项目点击事件
        document.querySelectorAll('.project-header').forEach(header => {
            header.addEventListener('click', function(e) {
                e.stopPropagation();

                const projectItem = this.parentElement;
                const subtasksContainer = projectItem.querySelector('.subtasks-container');
                const arrow = this.querySelector('.arrow');
                const projectId = projectItem.dataset.projectId;

                // 展开状态检测
                const isExpanded = subtasksContainer.classList.contains('show');

                if (isExpanded) {
                    // 收起逻辑
                    subtasksContainer.style.maxHeight = '0';
                    subtasksContainer.classList.remove('show');
                    arrow.textContent = '▼';
                    currentlyExpandedProject = null;
                    rightPanel.classList.remove('visible'); // 确保隐藏右侧面板
                } else {
                    // 收起所有其他项目
                    document.querySelectorAll('.subtasks-container').forEach(container => {
                        if (container !== subtasksContainer) {
                            container.style.maxHeight = '0';
                            container.classList.remove('show');
                            container.previousElementSibling.querySelector('.arrow').textContent = '▼';
                        }
                    });

                    // 展开当前项目
                    subtasksContainer.classList.add('show');
                    subtasksContainer.style.maxHeight = '600px';
                    arrow.textContent = '▲';
                    currentlyExpandedProject = projectItem;

                    // 确保右侧面板可见
                    rightPanel.classList.add('visible');
                    adjustRightPanelHeight(); // 调整高度

                    if (!projectItem.dataset.subtasksLoaded) {
                        loadSubtasks(projectId, projectItem.querySelector('.subtasks-list'));
                        projectItem.dataset.subtasksLoaded = true;
                    }
                }

                if (!isExpanded) {
                    // 在展开项目时加载员工列表
                    loadEmployeesForProject(projectId).then(() => {
                        // 如果有当前选中的子任务，重新标记已分配员工
                        if (currentSubtask && currentSubtask.projectId === projectId) {
                            fetchAssignedEmployees(currentSubtask.id)
                                .then(markAssignedEmployees);
                        }
                    });
                }
            });
        });

        // 新增：加载项目下的所有员工
        function loadEmployeesForProject(projectId) {
            return new Promise((resolve) => {
                const employeesList = document.getElementById('employeesList');
                employeesList.innerHTML = '<div class="employee-item loading">加载员工列表...</div>';

                fetch('/assigncontent/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': csrftoken,
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: JSON.stringify({ project_id: projectId })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.users) {
                        employeesList.innerHTML = '';
                        data.users.forEach(user => {
                            employeesList.appendChild(createEmployeeItem(user));
                        });
                        resolve();
                    }
                })
                .catch(error => {
                    console.error('加载员工失败:', error);
                    resolve(); // 即使失败也继续
                });
            });
        }


        // 子任务点击事件
        document.addEventListener('click', function(e) {
            const subtaskItem = e.target.closest('.subtask-item');
            if (subtaskItem && !subtaskItem.classList.contains('loading') &&
                !subtaskItem.classList.contains('no-subtasks') &&
                !subtaskItem.classList.contains('error')) {
                e.stopPropagation();

                const subtaskId = subtaskItem.dataset.subtaskId;
                const projectId = subtaskItem.dataset.projectId;
                console.log('点击的子任务ID:', subtaskId);

                // 发送AJAX请求
                fetch('/son_task/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': csrftoken,
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: JSON.stringify({
                        subtask_id: subtaskId
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        // 更新当前选中的子任务
                        currentSubtask = {
                            id: subtaskId,
                            name: subtaskItem.textContent.trim().split(' (工作量')[0],
                            projectId: projectId
                        };

                        // 标记已选中的员工
                        markAssignedEmployees(data.assigned_users || []);

                        // 更新UI
                        updateTaskAssignmentUI(currentSubtask.name);
                    }
                })
                .catch(error => {
                    console.error('请求失败:', error);
                });

                // 移除之前选中的样式
                document.querySelectorAll('.subtask-item').forEach(item => {
                    item.classList.remove('active');
                });

                // 添加当前选中样式
                subtaskItem.classList.add('active');
                currentSubtask = {
                    id: subtaskItem.dataset.subtaskId,
                    name: subtaskItem.textContent.trim().split(' (工作量')[0],
                    projectId: subtaskItem.dataset.projectId
                };

                // 加载员工列表
                loadEmployeesForSubtask(currentSubtask.projectId, currentSubtask.id, currentSubtask.name);
            }
        });

        function markAssignedEmployees(assignedUsers) {
            // 先取消所有选中状态
            document.querySelectorAll('#employeesList input[type="checkbox"]').forEach(checkbox => {
                checkbox.checked = false;
            });

            // 标记已分配员工
            assignedUsers.forEach(user => {
                const checkbox = document.querySelector(`#employeesList input[type="checkbox"][value="${user.id}"]`);
                if (checkbox) {
                    checkbox.checked = true;
                }
            });
        }

        // 更新右侧分配区域UI
        function updateTaskAssignmentUI(taskName) {
            const placeholder = document.getElementById('placeholder');
            const taskAssignment = document.getElementById('taskAssignment');

            placeholder.style.display = 'none';
            taskAssignment.style.display = 'flex';
            document.getElementById('selectedTaskTitle').textContent = `分配子任务: ${taskName}`;

            // 显示右侧面板（如果尚未显示）
            document.getElementById('rightPanel').classList.add('visible');
        }

        // 加载子任务函数
        function loadSubtasks(projectId, container) {
            container.innerHTML = '<div class="subtask-item loading">加载中...</div>';

            fetch('/assigncontent/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrftoken,
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify({
                    project_id: projectId
                })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(data => {
                if (data.success && data.subprojects && data.subprojects.length > 0) {
                    container.innerHTML = '';
                    data.subprojects.forEach(subproject => {
                        const subtaskItem = document.createElement('div');
                        subtaskItem.className = 'subtask-item';
                        subtaskItem.dataset.subtaskId = subproject.id;
                        subtaskItem.dataset.projectId = projectId;
                        subtaskItem.textContent = `${subproject.content} (工作量: ${subproject.predicted_effort || 0})`;
                        container.appendChild(subtaskItem);
                    });
                    setTimeout(() => {
                        if (container.classList.contains('show')) {
                            container.style.maxHeight = container.scrollHeight + 'px';
                        }
                    }, 0);
                } else {
                    container.innerHTML = '<div class="subtask-item no-subtasks">该项目暂无子任务</div>';
                }
            })
            .catch(error => {
                console.error('加载子任务出错:', error);
                container.innerHTML = '<div class="subtask-item error">加载子任务失败</div>';
            });
        }

        // 加载员工函数
        function loadEmployeesForSubtask(projectId, subtaskId, subtaskName) {
            const placeholder = document.getElementById('placeholder');
            const taskAssignment = document.getElementById('taskAssignment');
            const selectedTaskTitle = document.getElementById('selectedTaskTitle');
            const employeesList = document.getElementById('employeesList');

            placeholder.style.display = 'none';
            taskAssignment.style.display = 'flex';
            selectedTaskTitle.textContent = `分配子任务: ${subtaskName}`;
            employeesList.innerHTML = '<div class="employee-item loading">加载员工列表...</div>';

            fetch('/assigncontent/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrftoken,
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify({
                    project_id: projectId
                })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(data => {
                if (data.success && data.users && data.users.length > 0) {
                    employeesList.innerHTML = '';
                    data.users.forEach(user => {
                        const employeeItem = document.createElement('div');
                        employeeItem.className = 'employee-item';

                        employeeItem.innerHTML = `
                            <label class="checkbox-container">
                                ${user.full_name}
                                <input type="checkbox" value="${user.id}">
                                <span class="checkmark"></span>
                            </label>
                        `;

                        employeesList.appendChild(employeeItem);
                    });
                } else {
                    employeesList.innerHTML = '<div class="employee-item no-employees">该项目暂无员工</div>';
                }
            })
            .catch(error => {
                console.error('加载员工出错:', error);
                employeesList.innerHTML = '<div class="employee-item error">加载员工列表失败</div>';
            });
        }

        // 分配任务按钮点击事件
        // 修改分配任务按钮点击事件
        // 修改分配任务按钮点击事件
document.getElementById('assignBtn').addEventListener('click', function() {
    const btn = this;
    btn.disabled = true;
    btn.innerHTML = '分配中...';

    fetch('/save_assign/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': csrftoken
        },
        body: JSON.stringify({
            subtask_id: currentSubtask.id,
            employee_ids: Array.from(
                document.querySelectorAll('#employeesList input[type="checkbox"]:checked')
            ).map(el => el.value)
        })
    })
    .then(response => {
        if (!response.ok) throw new Error('HTTP错误');
        return response.json();
    })
    .then(data => {
        console.log("完整响应:", data);  // 调试

        if (data.success !== true) {  // 严格检查true
            throw new Error(data.message || '分配失败');
        }

        // 获取选中的员工姓名
        const names = Array.from(
            document.querySelectorAll('#employeesList input[type="checkbox"]:checked')
        ).map(el =>
            el.closest('label').textContent.trim()
        ).join('、');

        showNotification(`已成功分配给：${names}`, 'success');
    })
    .catch(error => {
        console.error('分配错误:', error);
        showNotification(error.message || '分配失败', 'error');
    })
    .finally(() => {
        btn.disabled = false;
        btn.textContent = '分配子任务';
    });
});

        // 显示通知函数
        function showNotification(message, type) {
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.textContent = message;
    document.body.appendChild(notification);

    // 显示动画
    setTimeout(() => notification.classList.add('show'), 10);

    // 3秒后自动消失
    setTimeout(() => {
        notification.classList.remove('show');
        setTimeout(() => document.body.removeChild(notification), 300);
    }, 3000);
}

        // 如果URL中有project_id参数，自动展开对应项目
        const urlParams = new URLSearchParams(window.location.search);
        const projectIdParam = urlParams.get('project_id');
        if (projectIdParam) {
            const projectItem = document.querySelector(`.project-item[data-project-id="${projectIdParam}"]`);
            if (projectItem) {
                const header = projectItem.querySelector('.project-header');
                header.click();

                // 如果已经有预加载的子任务，设置第一个为选中状态
                const firstSubtask = projectItem.querySelector('.subtask-item');
                if (firstSubtask && !firstSubtask.classList.contains('loading')) {
                    firstSubtask.click();
                }
            }
        }

        function adjustRightPanelHeight() {
            const rightPanel = document.getElementById('rightPanel');
            const headerHeight = document.querySelector('.project-header')?.offsetHeight || 0;
            rightPanel.style.height = `calc(100vh - ${headerHeight + 40}px)`;
        }

        // 初始化和监听窗口变化
        window.addEventListener('load', adjustRightPanelHeight);
        window.addEventListener('resize', adjustRightPanelHeight);
    });
    </script>
</body>
</html>